package framework.util;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

public class _ExcelUtil {
	
	/**
     * export导出请求头设置，设置字符集为UTF-8 <br/>
     * 参考博客:https://www.jianshu.com/p/b9ec05479de3
     */
	public static void export(HttpServletRequest request, HttpServletResponse response, String fileName, Workbook workbook) throws Exception {
        response.reset();
        initResponse(request, response, fileName);
        
        OutputStream outStream = null;
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } finally {
            outStream.close();
        }
    }
    
    /**
	 * @author 吴宇亮
	 * @data 2018-6-15
	 * @function 导出Excel的第一步，初始化response的编码格式为UTF-8
	 */
	public static void initResponse(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
		response.setCharacterEncoding("UTF-8");
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");// firefox浏览器
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");// 谷歌浏览器
		}
		response.setContentType("application/vnd.ms-excel"); // 防止乱码
		response.setHeader("Content-disposition", "attachment;filename= " + fileName + ".xls");
	}
}
